package com.cj.sys.web.security;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.cj.common.orm.Page;
import com.cj.common.orm.PropertyFilter;
import com.cj.common.orm.hibernate.EntityManager;
import com.cj.common.orm.hibernate.HibernateWebUtils;
import com.cj.common.web.struts2.CRUDActionSupport;
import com.cj.common.web.struts2.Struts2Utils;
import com.cj.sys.entity.security.Authority;
import com.cj.sys.entity.security.Dept;
import com.cj.sys.entity.security.User;
import com.cj.sys.service.security.AuthorityManager;
import com.cj.sys.service.security.SysConfigManager;
import com.cj.sys.service.security.UserManager;

/**
 * 用户管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数.
 * 
 * @author calvin
 */
@SuppressWarnings("serial")
public class UserAction extends CRUDActionSupport<User> {

	@Autowired
	private UserManager userManager;
	@Autowired
	private AuthorityManager authorityManager;

	// 角色相关属性
	private List<Authority> allAuthorities; // 全部可选角色列表
	private List<Long> checkedAuthorityIds; // 页面中钩选的角色id列表

	// 基本属性访问函数 //
	private Dept oldDept;
	private String oldPassword;
	private String newPassword;
	private HashMap<String,String> userTypeMap;
	@Override
	protected void prepareModel() throws Exception {
		if (getId() != null) {
			entity = userManager.get(getId());
		} else {
			entity = new User();
		}
	}

	// CRUD Action 函数 //

	@Override
	public String list(){
		try {
			HttpServletRequest request = Struts2Utils.getRequest();
			List<PropertyFilter> filters = HibernateWebUtils.buildPropertyFilters(request);
			getPage().setOrder(Page.ASC);
			getPage().setOrderBy("orderNum");
			setPage(userManager.search(getPage(),filters)) ;
			return SUCCESS;
		} catch (Exception e) {
			setErrMessage(e.getMessage(),e);
			return ERROR;
		}
	}

	@Override
	public String input() {
		try {
			allAuthorities = authorityManager.getAll();
			checkedAuthorityIds = entity.getAuthorityIds();
			return INPUT;
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}

	public String editMyself(){
		try {
			allAuthorities = authorityManager.getAll();
			checkedAuthorityIds = entity.getAuthorityIds();
			return "myself";
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}
	
	public String selfSave(){
		try {
			if(!StringUtils.isBlank(newPassword)){
				if(StringUtils.isBlank(oldPassword) || !oldPassword.equals(entity.getPassword())){
					setErrMessage("密码错误!");
					return ERROR;
				}
				entity.setPassword(newPassword);
			}
			userManager.save(entity);
			addActionMessage("保存用户成功");
			return "myself";			
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}
	public void prepareEditMyself() throws Exception {
		entity = userManager.getCurrentUser();
	}	
	public void prepareSelfSave() throws Exception {
		entity = userManager.getCurrentUser();
	}	
	
	@Override
	public void prepareSave() throws Exception {
		if (getId() != null) {
			entity = userManager.get(getId());
			oldDept = entity.getDept();
			entity.setDept(null);
		} else {
			entity = new User();
		}
	}
	@Override
	public String save() {
		try {
			// 根据页面上的checkbox 整合User的Roles Set
			HibernateWebUtils.mergeByCheckedIds(entity.getAuthorities(), checkedAuthorityIds, Authority.class);
			userManager.save(entity);
			addActionMessage("保存用户成功");
			return list();			
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}

	@Override
	public String delete(){
		try {
			userManager.delete(getId());
			addActionMessage("删除用户成功");
			return list();
		} catch (Exception e) {
			setErrMessage(e.getMessage(), e);
			return ERROR;
		}
	}

	// 其他属性访问函数与Action函数 //


	/**
	 * 支持使用Jquery.validate Ajax检验用户名是否重复.
	 */
	public String checkLoginName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String loginName = request.getParameter("code");
		String orgLoginName = request.getParameter("orgLoginName");

		if (userManager.isLoginNameUnique(loginName, orgLoginName)) {
			Struts2Utils.renderText("true");
		} else {
			Struts2Utils.renderText("false");
		}
		// 因为直接输出内容而不经过jsp,因此返回null.
		return null;
	}

	@Override
	public EntityManager getEntityManager() {
		return userManager;
	}


	public List<Long> getCheckedAuthorityIds() {
		return checkedAuthorityIds;
	}

	public void setCheckedAuthorityIds(List<Long> checkedAuthorityIds) {
		this.checkedAuthorityIds = checkedAuthorityIds;
	}

	public List<Authority> getAllAuthorities() {
		return allAuthorities;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public HashMap<String, String> getUserTypeMap() {
		return SysConfigManager.configByType(User.CONFIG_USER_TYP);
	}
	
}
